import java.io.IOException;
import java.util.Enumeration;

import net.jxta.discovery.DiscoveryEvent;
import net.jxta.discovery.DiscoveryListener;
import net.jxta.discovery.DiscoveryService;
import net.jxta.document.Advertisement;
import net.jxta.document.AdvertisementFactory;
import net.jxta.document.Document;
import net.jxta.document.MimeMediaType;
import net.jxta.id.IDFactory;
import net.jxta.pipe.OutputPipeEvent;
import net.jxta.pipe.OutputPipeListener;
import net.jxta.platform.NetworkManager.ConfigMode;
import net.jxta.protocol.DiscoveryResponseMsg;
import net.jxta.protocol.PipeAdvertisement;
import advs.ServiceAdvertisement;
import advs.ServicePublisherAdvertisement;

public class ServiceManager extends JxtaApplication {

	public ServiceManager() {
		super("ServiceManagerFinder");
	}
	
	@Override
	public void Start() {

		if (!Initialize(ConfigMode.EDGE, "ServiceManager", false)) {
			return;
		}
		try {

			String serviceName = "*Math*";

			Log("Searching for remote advs");

//			Enumeration<Advertisement> advs = getDiscoveryService()
//					.getLocalAdvertisements(DiscoveryService.ADV,
//							ServicePublisherAdvertisement.ServiceNameTag,
//							serviceName);
//
//			if (advs.hasMoreElements()) {
//				System.out.println("Local advertisments:");
//				processAdvertisments(advs);
//			}

			getDiscoveryService().getRemoteAdvertisements(null,
					DiscoveryService.ADV,
					ServicePublisherAdvertisement.ServiceNameTag, serviceName,
					100);

			Log("Search for remote advs started");

		} catch (Exception e) {
			Log("Error:" + e.getMessage());
		}
	}

	@Override
	public void discoveryEvent(DiscoveryEvent event) {
		DiscoveryResponseMsg response = event.getResponse();
		Enumeration<Advertisement> advertisments = response.getAdvertisements();
		processAdvertisments(advertisments);

	}

	private void processAdvertisments(Enumeration<Advertisement> advertisments) {
		while (advertisments.hasMoreElements()) {
			Advertisement genericAdv = advertisments.nextElement();
			String advType = genericAdv.getAdvType();
			Log(advType+" found");
			if (advType == ServicePublisherAdvertisement.getAdvertisementType()) {
				ServicePublisherAdvertisement adv = (ServicePublisherAdvertisement)genericAdv;
				System.out.println("Found:");
				
				
//				try {
//					Document doc = adv.getDocument(MimeMediaType.XMLUTF8);
//					doc.sendToStream(System.out);
//				} catch (Exception e) {
//					System.out.println("ERROR4:" + e.getMessage());
//
//				}

				ForwardPublishServices(adv);
			}
		}
		Log("starting threads");
		StartThreads();
	}

	private void ForwardPublishServices(ServicePublisherAdvertisement advFound) {

		Log("Se forwardeaza serviciul "
				+ advFound.getServiceName());
		int expiration = 300 * 1000;
		int lifetime = 300 * 1000;
		int repeatTime = 300 * 1000;

		ServiceAdvertisement adv = (ServiceAdvertisement) AdvertisementFactory
				.newAdvertisement(ServiceAdvertisement.getAdvertisementType());

		adv.setId(IDFactory.newCodatID(getGroup().getPeerGroupID()).toString());

		adv.setPipeAdvID(advFound.getPipeAdvID());

		adv.setServiceName(advFound.getServiceName());

		adv.setSolverAdvID(advFound.getId().toString());
		
		adv.setSolverID(advFound.getPeerID().toString());

		ThreadPublisher publisherThread = new ThreadPublisher(this);

		publisherThread.setPrintAdvOnPublish(true);

		publisherThread.addAdv(adv);

		publisherThread.setExpiration(expiration);
		publisherThread.setLifetime(lifetime);
		publisherThread.setRepeatTime(repeatTime);

		publisherThread.setName("Service." + adv.getServiceName());
		publisherThread.setPeerToPublishTo("");
		publisherThread.setPrintAdvOnPublish(true);
		getLoopPublishingThreads().put("Service:" + adv.getServiceName(),
				publisherThread);

	}


}
